<?php
/*调试输出*/
function ddd($var, $exit=false, $printR=false)
{
    if(headers_sent() === false){ header("Content-type:text/html; charset=utf-8"); }
    if($printR){
        echo '<pre>';
        print_r($var);
        echo '</pre>';
    }else{
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if(!extension_loaded('xdebug')){
            $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
            $output = '<pre>'. htmlspecialchars($output, ENT_QUOTES).'</pre>';
        }
        echo $output;
    }
    if ($exit){exit;}
    else{return;}
}

//得到表名称
function tb($t = '')
{
    return \app\common\base\TableMySQL::getTableName($t);
}

/**
 * 把返回的数据集转换成Tree
 *
 * @param array $list 要转换的数据集
 * @param string $pk
 * @param string $pid parent标记字段
 * @param string $child 子数组标记
 * @param int $root
 *
 * @return array
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_sub', $root = 0)
{
    // 创建Tree
    $tree = [];
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}


/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree 原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array $list 过渡用的中间数组，
 * @return array        返回排过序的列表数组
 */
function tree_to_list($tree, $child = '_sub', $order = 'id', &$list = array())
{
	if (is_array($tree)) {
		$refer = array();
		foreach ($tree as $key => $value) {
			$reffer = $value;
			$list[] = $reffer;
			if (isset($reffer[$child])) {
				tree_to_list($value[$child], $child, $order, $list);
			}
		}
	}
	foreach($list as &$l) {
		if($l[$child]) {
			unset($l[$child]);
			$l['has_sub'] = true;
		}
	}
	return $list;
}

/**
 * 把多维数组转化成一维数组
 *
 * @param array $arr 需要转换的数组，必须有相同的子节点
 * @param string $sub 子节点名称
 * @param array &$rs 返回的引用数组
 *
 * @return void
 */
function float_array($arr=[], $sub='_sub', &$rs)
{
    if(empty($arr)){ return; }
    foreach($arr as $v){
        $tmp2 = $v;
        if(isset($tmp2[$sub])){
            unset($tmp2[$sub]);
            $rs[] = $tmp2;
            float_array($v[$sub], $sub, $rs);
        }else{
            $rs[] = $v;
        }
    }
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

//判断是否为email
function is_email($str)
{
    return (filter_var($str, FILTER_VALIDATE_EMAIL) === false) ? false : true;
}

//手机
function is_mobile($string)
{
    return preg_match('/^1[345678]+\d{9}$/', $string);
}

//文件后缀名
function file_suffix($filename, $scope=10)
{
    return strtolower(trim(substr(strrchr($filename, '.'), 1, $scope)));
}

/**
 * 获取IP地理位置接口
 *
 * @param string  $ip
 * @param boolean $to_string
 *
 * @return mixed
 */
function ip_geo($ip='', $to_string=false)
{
    $url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip;
    $ip_info = json_decode(file_get_contents($url), true);
    if($ip_info['code'] !== 0) { return (true === $to_string) ? '' : []; }
    $ip_info = $ip_info['data'];
    if(true === $to_string){
        $tmp = [];
        if($ip_info['country'] != ''){ $tmp[] = $ip_info['country']; }
        if($ip_info['area'] != ''){ $tmp[] = $ip_info['area']; }
        if($ip_info['region'] != ''){ $tmp[] = $ip_info['region']; }
        if($ip_info['city'] != ''){ $tmp[] = $ip_info['city']; }
        if($ip_info['county'] != ''){ $tmp[] = $ip_info['county']; }
        return empty($tmp) ? '' : implode('-', $tmp);
    }else{
        return $ip_info;
    }
}

//组装返回信息
function rs($c=0, $m='', $d=[])
{
    $rt = [];
    $rt['c'] = intval($c);
    $rt['m'] = $m;
    $rt['d'] = $d;
    return $rt;
}

//由字符串得到整数数组
function get_int_array_from_string($str='', $d=',', $unique=true, $positive=true)
{
    $str = trim($str); if($str == ''){ return []; }
    $d = trim($d); if($d == ''){ $d = ','; }
    $rs = [];
    $t = explode($d, $str);
    if( ! empty($t)){
        foreach($t as $v){
            $v = intval($v);
            if($positive && $v<1){
                continue;
            }
            $rs[] = $v;
        }
        if($unique){
            $rs = array_unique($rs);
        }
    }
    return $rs;
}

//创建文件夹
function mk_dir($dir='', $mode=0777)
{
    if( ! is_dir($dir)){
        mk_dir(dirname($dir), $mode);
        $old = umask(0);
        @mkdir($dir, $mode);
        umask($old);
        return true;
    }
    return true;
}

/*
 * 删除指定目录中的所有目录
 * 可扩展增加一些选项（如是否删除原目录等）
 * 删除文件敏感操作谨慎使用
 *
 * @param $dir 目录路径
 * @param array $file_type指定文件类型
 *
 * @return void
 */
function del_dir($dir='', $file_type='')
{
    if( ! is_dir($dir)){ return; }
    $files = scandir($dir);
    foreach($files as $filename)
    {
        if($filename!='.' && $filename!='..'){
            $fullPath = $dir."/".$filename;
            if(!is_dir($fullPath)){
                if(empty($file_type)){
                    unlink($fullPath);
                }else{
                    if(is_array($file_type)){
                        //正则匹配指定文件
                        if(preg_match($file_type[0], $filename)){ unlink($fullPath); }
                    }else{
                        //指定包含某些字符串的文件
                        if(false!=stristr($filename, $file_type)){ unlink($fullPath); }
                    }
                }
            }else{
                del_dir($fullPath);
                rmdir($fullPath);
            }
        }
    }
}

function array_map_recursive($filter, $data) {
    $result = array();
    foreach ($data as $key => $val) {
        $result[$key] = is_array($val)
            ? array_map_recursive($filter, $val)
            : call_user_func($filter, $val);
    }
    return $result;
}

//过滤输入数据库数据
function data_in($data, $filters='trim,addslashes')
{
    $filters = explode(',', $filters);
    foreach($filters as $filter){
        if(function_exists($filter)) {
            $data = is_array($data) ? array_map_recursive($filter, $data) : $filter($data);
        }
    }
    return $data;
}

//过滤输出数据库数据
function data_out($data, $filters='stripslashes')
{
    $filters = explode(',', $filters);
    foreach($filters as $filter){
        if(function_exists($filter)) {
            $data = is_array($data) ? array_map_recursive($filter, $data) : $filter($data);
        }
    }
    return $data;
}

//生成唯一
function get_uuid()
{
    return md5(uniqid(mt_rand(), true));
}

/**
 * 取得请求参数
 *
 * @param string $name 前缀 get. post. request.
 * @param mixed  $default
 * @param mixed  $filter
 *
 * @return mixed
 */
function I($name='', $default=null, $filter=null)
{
    if(0 === strpos($name, 'request.')){
        $name = str_replace('request.', 'param.', $name);
    }
    if(0 === strpos($name, 'get.')){
        $name = str_replace('get.', 'param.', $name);
    }
    return input($name, $default, $filter);
}

/**
 * 遍历树结构,获取其中某项元素的值
 * 用法
 *  $menu = include(APP_PATH .'Common/Conf/menu.php');
 *  $list = tree_get_value($menu, 'name');  //返回name一维数组
 *  $list = tree_get_value($menu);  //返回二维维数组
 *
 * @author linshiling
 *
 * @param array  $tree     树结构
 * @param string $getKey   元素名
 * @param string $childKey  子元素key
 *
 * @return array
 */
function tree_to_array($tree = [], $getKey = '', $childKey = 'subs')
{
    $list = [];
    foreach ($tree as $item) {
        $subs = isset($item[$childKey]) ? $item[$childKey] : [];
        unset($item[$childKey]);
        $list[] = ($getKey && isset($item[$getKey])) ? $item[$getKey] : $item;
        if($subs) {
            $subList = tree_to_array($subs, $getKey, $childKey);
            $list = array_merge($list, $subList);
        }
    }
    $list = array_filter($list);
    $list = array_values($list);    //key重新排序,否则json_encode时会变成对象而不是数组
    return $list;
}


//输出碎片内容
function piece($id)
{
	$section = M('piece')->find($id);
	return $section ? $section['content'] : '{无此碎片:' . $id . '}';
}
//输出碎片组(多图模式)
function repeat($id)
{
	$ads = M('repeat')->find($id);
	if(!$ads['st']) return array();
	$data = M('repeat_item')->where("pid = $id")->select();
	return $data;
}



/**
 * 按照key组合数组
 *
 * @param    array
 * @param    string
 *
 * @return   array
 **/
function singleGroup($array, $key)
{
	if (empty($array)) {
		return array();
	}

	$array1 = array();

	foreach ($array as $val) {
		$array1[$val[$key]] = $val;
	}

	return $array1;
}

//M()->query();之后取一个字段
function getOne($sql)
{
	$rs = Db::query($sql);
	return current($rs[0]);
}

//M()->query();之后取一条记录
function getRow($sql)
{
	$rs = Db::query($sql);
	return $rs[0];
}

//取一列
function getCol($sql, $mod = 'array')
{
	$rs = Db::query($sql);
	foreach ($rs as &$r) {
		$r = current($r);
	}
	return $mod == 'array' ? $rs : implode(',', $rs);
}

function getMap($sql)
{
	$rs  = Db::query($sql);
	$arr = array();
	foreach ($rs as $r) {
		$k       = current($r);
		$v       = array_pop($r);
		$arr[$k] = $v;
	}
	return $arr;
}

//获取分类名
function getCate($id)
{
	static $map;
	if (!$map) {
		$map = getMap("SELECT id, title FROM cate");
	}
	$name = $map[$id];
	return $name ? $name : "无此分类：$id";
}

/**
 * 通用条件解析
 *
 * @param string $table         主表名
 * @param string $mod           如果是join模式,普通键值为a表字段,下划线开头的为b表字段
 * @param array $disabledField  禁止用于搜索的字段
 * @return string
 */
function parseWhere($mod = '', $disabledField = array())
{
	//对分类搜索特殊处理，去掉id后面的
	cate_where();

	if(is_string($disabledField)) {
		$disabledField = explode(',', $disabledField);
		foreach($disabledField as $k => &$s) {
			$s = trim($s);
			if(!$s) unset($disabledField[$k]);
		}
	}
	if ($_POST ) {
		$params = $_POST;
	} else {
		$params = $_GET;
	}
	$where = array();
	foreach ($params as $field => $v) {
		if (!is_array($v)) {
			$v = trim($v);
		}
		if (in_array($field, array('p', 'order', 'prop', 'size', 'page'))) continue;
		if ($v === '-1') continue;
		if ($v === '') continue;
		if (strpos($field, '_no_search')) continue;
		$prev = '';
		if ($mod == 'join') {
			if ($field[0] == '_') {
				$prev  = 'b.';
				$field = substr($field, 1, 99);
			} else {
				$prev = 'a.';
			}
		}

		//部门包含下级部门
		if (strpos($field, '_not_in')) {
			$field   = str_replace('_not_in', '', $field);
			$where[] = array("{$prev}$field", 'not in', $v);
		} else if (strpos($field, '_in')) {
			$field   = str_replace('_in', '', $field);
			$where[] = array("{$prev}$field", 'in', $v);
		} else if (strpos($field, '_like')) {
			$field   = str_replace('_like', '', $field);
			$where[] = array("{$prev}$field", 'like', "%$v%");
		} else if (strpos($field, '_lt')) {
			$field   = str_replace('_lt', '', $field);
			$where[] = array("{$prev}$field", '<', $v);
		} else if (strpos($field, '_gt')) {
			$field   = str_replace('_gt', '', $field);
			$where[] = array("{$prev}$field", '>', $v);
		} else if (strpos($field, '_neq')) {
			$field   = str_replace('_neq', '', $field);
			$where[] = array("{$prev}$field", 'neq', $v);
		} else {
			if ($v == 'null') {
				$where[] = array("{$prev}$field", 'NULL');
			} else if ($v == 'not_null') {
				$where[] = array("{$prev}$field", 'NOT NULL');
			} else {
				$where[] = array("{$prev}$field", 'EQ', $v);
			}
		}
	}
	foreach ($where as $k => $v) {
		$f = str_replace(array('a.', 'b.'), '', $k);
		if(in_array($f, $disabledField)) unset($where[$k]);
	}
	return $where;
}

//站点内容搜索
function siteWhere()
{
	$site = request()->header('site-id');
	if(!$site) return;
	if(request()->isPost()) {
		$_POST['site'] = $site;
	}else{
		$_GET['site'] = $site;
	}
}

function M($table)
{
	return Db::table($table);
}

function mdb($table)
{
	return Db::connect('mongo')->name($table);
}


//对分类修改进行特殊处理(取整，包含下级）
function cate_where()
{
	if ($_POST['cate_id']) {
		$_POST['cate_id'] = (int) $_POST['cate_id'];
		$cate_id = (int) $_POST['cate_id'];
	}elseif ($_GET['cate_id']) {
		$_GET['cate_id'] = (int) $_GET['cate_id'];
		$cate_id = (int) $_GET['cate_id'];
	}else{
		return;
	}
	$son = getCol("SELECT * FROM cate WHERE pid = $cate_id");
	if($son) {
		$son_son = getCol("SELECT * FROM cate WHERE pid in(". implode(',', $son) .")");
		$son = array_merge($son, $son_son);
	}
	$son[] = $cate_id;
	if(count($son) > 1) {
		if ($_POST['cate_id']) {
			$_POST['cate_id_in'] = $son;
			unset($_POST['cate_id']);
		}else{
			$_GET['cate_id_in'] = implode(',', $son);
			unset($_GET['cate_id']);
		}
	}
}


//id转姓名
function getAdmin($id)
{
	static $map;
	if (!$map) {
		$map = getMap("SELECT id, name FROM admin");
	}
	return $map[$id];
}

//json返回正常结果
function ok($data = array())
{
	if(is_array($data) || is_object($data)) {
		$data = ['c' => 0,'m' => 'ok','d' => $data];
	}else{
		$data = ['c' => 0,'m' => $data,'d' => []];
	}
	header("Content-type:application/json;charset=utf-8");
	echo json_encode($data, 256);
	exit;
}

//json返回错误结果
function error($msg)
{
	if(is_array($msg) || is_object($msg)) {
		$data = ['c' => 1,'m' => 'error','d' => $msg];
	}else{
		$data = ['c' => 1,'m' => $msg,'d' => []];
	}
	header("Content-type:application/json;charset=utf-8");
	echo json_encode($data, 256);
	exit;
}

//只保留数组中的有限字段
function allow_field($data, $fields)
{
	$fields = explode(',', $fields);
	foreach ($fields as $k => $f) {
		$fields[$k] = trim($f);
		if(!$fields[$k]) unset($fields[$k]);
	}
	foreach ($data as $k => $d) {
		if(!in_array($k, $fields)) unset($data[$k]);
	}
	return $data;
}

//排除数组中的字段
function disable_field($data, $fields)
{
	$fields = explode(',', $fields);
	foreach ($fields as $k => $f) {
		$fields[$k] = trim($f);
		if(!$fields[$k]) unset($fields[$k]);
	}
	foreach ($data as $k => $d) {
		if(in_array($k, $fields)) unset($data[$k]);
	}
	return $data;
}

//前端输出图片
function img($url)
{
	//$url = str_replace('api.cms.lc', 'api.i-sanger.cn', $url);
	//$url = str_replace('www.cms.lc', 'www.i-sanger.cn', $url);
	//$url = str_replace('api.cms.cn', 'api.i-sanger.cn', $url);
	//$url = str_replace('www.cms.cn', 'www.i-sanger.cn', $url);
	return $url;
}